package com.zbkj.crmeb.task.plat.bieyang;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.crmeb.core.config.RestTemplateConfig;
import com.factory.TaskParamsDto;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.utils.DateUtil;
import com.utils.PriceUtil;
import com.utils.monitor.DingMsgEnum;
import com.utils.monitor.DingTalkMsgUtil;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.zbkj.crmeb.chant.service.ICategoryMatchService;
import com.zbkj.crmeb.enums.AreaTypeEnum;
import com.zbkj.crmeb.enums.BusinessTypeEnums;
import com.zbkj.crmeb.handler.orderproduct.OrderProductContext;
import com.zbkj.crmeb.handler.orderproduct.OrderProductInterface;
import com.zbkj.crmeb.plat.by.dto.*;
import com.zbkj.crmeb.plat.by.dto.attributes.SaleAttribute;
import com.zbkj.crmeb.store.dao.StoreOrderDao;
import com.zbkj.crmeb.store.model.*;
import com.zbkj.crmeb.store.response.StoreCartResponse;
import com.zbkj.crmeb.store.response.StoreProductCartProductInfoResponse;
import com.zbkj.crmeb.store.service.*;
import com.zbkj.crmeb.task.plat.AbstractPlatOperate;
import com.zbkj.crmeb.task.plat.bieyang.dto.*;
import com.zbkj.crmeb.tools.model.MoneyExchange;
import com.zbkj.crmeb.tools.service.MoneyExchangeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.*;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 别样订单捞取
 *
 * @author: wsl
 * @date: 2024/1/29 0029 22:08
 * @ClassName: BieYangOrderTask
 */
@Component("bieYangOrderTask")
@Configuration
@Slf4j
public class BieYangOrderTaskV2 extends AbstractPlatOperate<TaskParamsDto> implements ApplicationRunner {
    private static final Logger logger = LoggerFactory.getLogger(BieYangOrderTaskV2.class);
    @Autowired
    RestTemplateConfig restTemplateConfig;
    @Autowired
    private StoreOrderService storeOrderService;
    @Autowired
    private StoreOrderInfoService storeOrderInfoService;
    @Autowired
    private StoreProductService storeProductService;
    @Autowired
    private RelationService relationService;
    @Autowired
    private StoreProductAttrService storeProductAttrService;
    @Autowired
    private StoreProductAttrValueService storeProductAttrValueService;
    @Resource
    private StoreOrderDao storeOrderDao;
    @Resource
    private StoreBrandService storeBrandService;
    @Resource
    private ICategoryMatchService categoryMatchService;
    @Resource
    private PriceUtil priceUtil;
    @Resource
    private MoneyExchangeService moneyExchangeService;
    @Qualifier("byOrderProductHandler")
    @Autowired
    private OrderProductInterface orderProductInterface;

    @Value("${by.plat.url}")
    private String platUrl;

    private static String platKey;
    @Value("${by.plat.key}")
    public void setKey(String key) {
        platKey = key;
    }


    @XxlJob("uploadProduct")
    public void uploadProduct(){
        OrderProductContext orderProductContext = new OrderProductContext();
        orderProductContext.setProductId(XxlJobHelper.getJobParam());
        Result execute = orderProductInterface.execute(orderProductContext);
        DingTalkMsgUtil.sendMsg(DingMsgEnum.PLAT,JSON.toJSONString(execute));
    }

    @XxlJob("fetchOrderOfBieYang")
    public void fetch(){
        String logID = UUID.randomUUID().toString();
        logger.info("logID:[{}]", logID);
        logger.info("[{}] fetchOrderOfBieYang 入口", logID);
        Date date = new Date();
        Long end = date.getTime();
        // 20天
        Long before = end- ( 24 * 60 * 60 * 1000 * 20);
        List<BieYangDataDto> bieYangDataDtos = new ArrayList<>();
        BieYangOrderQueryDto bieYangOrderQueryDto = new BieYangOrderQueryDto();
        bieYangOrderQueryDto.setLimit(100);
        bieYangOrderQueryDto.setPlacedAtAfter(before);
        bieYangOrderQueryDto.setPlacedAtBefore(end);
        List<Integer> ids = new ArrayList<>();
        try {
            boolean flag = true;
            // 爬取别样订单数据
            while(flag){
                MultiValueMap<String,String> header = new LinkedMultiValueMap<>();
                header.put("Authorization",Collections.singletonList(platKey));
//                logger.info("[{}] 爬取别样订单数据请求：{},{},{}", logID, platUrl+"/order/api/v1/orders", JSON.toJSONString(bieYangOrderQueryDto), header);

                String result = post(platUrl+"/order/api/v1/orders", JSON.toJSONString(bieYangOrderQueryDto), header);
//                logger.info("[{}] 爬取别样订单数据响应：{}", logID, result);

                if (StringUtils.isBlank(result)){
                    return;
                }
                BieYangResultDto bieYangResultDto = JSONObject.parseObject(result, BieYangResultDto.class);
                if (null == bieYangResultDto || CollectionUtils.isEmpty(bieYangResultDto.getData())){
                    return;
                }
                bieYangOrderQueryDto.setCursor(bieYangResultDto.getCursor());
                bieYangDataDtos.addAll(bieYangResultDto.getData());
                flag = bieYangResultDto.getHasMore();
            }
//            logger.info("[{}] 爬取别样订单数据全部：{}", logID, JSON.toJSONString(bieYangDataDtos));

            // 校验别样订单状态
            validateBieYangOrderStatus(bieYangDataDtos);
//            logger.info("[{}] 校验别样订单状态后：{}", logID, JSON.toJSONString(bieYangDataDtos));
            if (CollectionUtils.isEmpty(bieYangDataDtos)){
                return;
            }
            // 处理拆单订单
            handleSplitOrder(bieYangDataDtos);
//            logger.info("[{}] 处理拆单订单后：{}", logID, JSON.toJSONString(bieYangDataDtos));
            // 校验订单是否存在
            validateOrderExist(bieYangDataDtos);
//            logger.info("[{}] 校验订单是否存在后：{}", logID, JSON.toJSONString(bieYangDataDtos));
            if (CollectionUtils.isEmpty(bieYangDataDtos)){
                return;
            }
            // 组装订单数据
            for (BieYangDataDto bieYangDataDto : bieYangDataDtos) {
                StoreOrder storeOrder = assembledStoreOrder(bieYangDataDto);
//                logger.info("[{}] 组装订单数据后：{}", logID, JSON.toJSONString(storeOrder));
                if (null == storeOrder){
                    return;
                }
                // 新增订单
                boolean b = storeOrderService.saveOrUpdate(storeOrder);
                if (!b){
                    log.error("新增订单异常,{}",JSON.toJSONString(storeOrder));
                    continue;
                }
                StoreOrder queryStoreOrder = storeOrderService.getOne(Wrappers.<StoreOrder>lambdaQuery().eq(StoreOrder::getOrderId, storeOrder.getOrderId()).last("limit 1"));
//                logger.info("[{}] 查询保存订单：{}", logID, JSON.toJSONString(queryStoreOrder));
                if (null == queryStoreOrder){
                    log.error("查询保存订单异常,{}",JSON.toJSONString(storeOrder));
                    continue;
                }
                try {
                    List<StoreOrderInfo> storeOrderInfos = assembledStoreOrderInfo(bieYangDataDto,queryStoreOrder);
//                    logger.info("[{}] 组装StoreOrderInfo数据后：{}", logID, JSON.toJSONString(storeOrderInfos));
                    storeOrderInfoService.saveOrUpdateBatch(storeOrderInfos);
                    DingTalkMsgUtil.sendMsg(DingMsgEnum.PLAT,"别样创建订单："+storeOrder.getOrderId());
                }catch (Exception e) {
                    log.error("组装商品数据异常:",e);
                    ids.add(queryStoreOrder.getId());
                    throw new RuntimeException(e);
                }
            }
        }
        catch (Exception e){
            log.error("别样创建订单异常:",e);
            // 删除订单
            storeOrderService.removeByIds(ids);
            throw new RuntimeException(e);
        }

    }

    private void handleSplitOrder(List<BieYangDataDto> bieYangDataDtos) {
        if (CollectionUtils.isEmpty(bieYangDataDtos)){
            return;
        }
        Iterator<BieYangDataDto> iterator = bieYangDataDtos.iterator();
        List<BieYangDataDto> splitDataDtos = new ArrayList<>();
        while (iterator.hasNext()){
            BieYangDataDto bieYangDataDto = iterator.next();
            if (null!=bieYangDataDto.getInfoSummary()&&null!=bieYangDataDto.getInfoSummary().getSplit()&&bieYangDataDto.getInfoSummary().getSplit()){
                splitDataDtos.add(bieYangDataDto);
                iterator.remove();
            }
        }
        if (CollectionUtils.isEmpty(splitDataDtos)){
            return;
        }
        Map<String, BieYangDataDto.SkuInfo> splitSkuMap = new HashMap<>();
        for (BieYangDataDto splitDataDto : splitDataDtos) {
            List<BieYangDataDto.SkuInfo> skus = splitDataDto.getSkus();
            for (BieYangDataDto.SkuInfo skuInfo : skus) {
                splitSkuMap.put(skuInfo.getBasicInfo().getSkuId()+"#"+skuInfo.getBasicInfo().getProductId(),skuInfo);
            }
        }

        for (BieYangDataDto splitDataDto : splitDataDtos) {
            BieYangInfoSummaryDto infoSummary = splitDataDto.getInfoSummary();
//            List<BieYangDataDto.SkuInfo> skus = splitDataDto.getSkus();
//            for (BieYangDataDto.SkuInfo skuInfo : skus) {
//                splitSkuMap.put(skuInfo.getBasicInfo().getProductId()+"#"+skuInfo.getBasicInfo().getSkuId(),skuInfo);
//            }
            List<BieYangOrderClearanceInfoDto> subClearanceInfo = splitDataDto.getSubClearanceInfo();
            if (CollectionUtils.isEmpty(subClearanceInfo)){
                continue;
            }
            for (BieYangOrderClearanceInfoDto bieYangOrderClearanceInfoDto : subClearanceInfo) {
                BieYangDataDto newBieYangDataDto = JSON.parseObject(JSON.toJSONString(splitDataDto), BieYangDataDto.class);
                BieYangInfoSummaryDto newInfoSummary = newBieYangDataDto.getInfoSummary();
                // 主单号
                newInfoSummary.setMainOrderId(newInfoSummary.getOrderId());
                // 单号
                newInfoSummary.setOrderId(bieYangOrderClearanceInfoDto.getSubOrderNum());
                // 金额
                newInfoSummary.setTotalItemPrice(bieYangOrderClearanceInfoDto.getTotalActualPay());
//                newInfoSummary.setTaxAmount(bieYangOrderClearanceInfoDto.gett());
                // 清关信息
                newBieYangDataDto.setClearanceInfo(bieYangOrderClearanceInfoDto);
                List<BieYangSkuIdsInfo> skuIds = bieYangOrderClearanceInfoDto.getSkuIds();
                List<BieYangDataDto.SkuInfo> newSkuInfos = new ArrayList<>();
                for (BieYangSkuIdsInfo skuIdInfo : skuIds) {
                    String key = skuIdInfo.getSkuId() + "#" + skuIdInfo.getProductId();
                    if (!splitSkuMap.containsKey(key)){
                        continue;
                    }
                    BieYangDataDto.SkuInfo skuInfo = splitSkuMap.get(key);
                    newSkuInfos.add(skuInfo);
                }
                newBieYangDataDto.setSkus(newSkuInfos);

                bieYangDataDtos.add(newBieYangDataDto);
            }

        }


    }

    private void validateBieYangOrderStatus(List<BieYangDataDto> bieYangDataDtos) {
        Iterator<BieYangDataDto> iterator = bieYangDataDtos.iterator();
        while (iterator.hasNext()){
            BieYangDataDto bieYangDataDto = iterator.next();
            // 基础判空
            if (null == bieYangDataDto.getInfoSummary() || null == bieYangDataDto.getSkus()){
                iterator.remove();
            }
            if (!Objects.equals(bieYangDataDto.getInfoSummary().getOrderStatus(),"PAYMENT_RECEIVED")){
                iterator.remove();
            }
        }
    }

    private List<StoreOrderInfo> assembledStoreOrderInfo(BieYangDataDto bieYangDataDto, StoreOrder queryStoreOrder) {
        // 商品
        List<BieYangDataDto.SkuInfo> skus = bieYangDataDto.getSkus();
        // 清关信息
        BieYangOrderClearanceInfoDto clearanceInfo = bieYangDataDto.getClearanceInfo();
        // 发件人信息
        BieYangAddressDto shippingAddress = bieYangDataDto.getShippingAddress();
        // 订单信息
        BieYangInfoSummaryDto infoSummary = bieYangDataDto.getInfoSummary();


        List<StoreOrderInfo> storeOrderInfos = new ArrayList<>();

        int index = 1;
        for (BieYangDataDto.SkuInfo skuInfo : skus) {
            BieYangGoodsAmountInfoDto amountInfo = skuInfo.getAmountInfo();
            // 优惠金额
            BieYangGoodsAmountInfoDto.MerchantPromotion merchantPromotion = null;
            if (null != amountInfo){
                merchantPromotion= amountInfo.getMerchantPromotion();
            }
            BieYangGoodsBasicInfoDto basicInfo = skuInfo.getBasicInfo();
            BieYangGoodsClearanceAmountDto clearanceAmount = skuInfo.getClearanceAmount();

            // 查询商品唯一属性
            StoreProductAttrValue storeProductAttrValue = getProductAttrValueInfo(basicInfo);
            if (null == storeProductAttrValue){
                DingTalkMsgUtil.sendMsg(DingMsgEnum.PLAT,String.format("订单匹配商品sku失败:%s， %s， %s",basicInfo.getMerchantSkuId(),basicInfo.getProductId(),basicInfo.getSkuId()));
                throw new RuntimeException("根据商户SKU查询商品异常");
            }
            // 根据商品属性匹配商品
            StoreProduct storeProduct = storeProductService.getOne(Wrappers.<StoreProduct>lambdaQuery().eq(StoreProduct::getId, storeProductAttrValue.getProductId()));
            if (null == storeProduct){
                throw new RuntimeException("商品不存在");
            }

            StoreOrderInfo storeOrderInfo = new StoreOrderInfo();
            storeOrderInfo.setOrderId(queryStoreOrder.getId());
//            storeOrderInfo.setInfo("{}");
            storeOrderInfo.setUnique(UUID.randomUUID().toString());
            storeOrderInfo.setOrderInfoId(queryStoreOrder.getOrderId()+"_"+index);
            storeOrderInfo.setDeliveryAddress(StringUtils.defaultString(shippingAddress.getAddress1(),shippingAddress.getAddress2()));
            storeOrderInfo.setChildOrderNumber("SUB_"+queryStoreOrder.getOrderId()+"_"+index);
            storeOrderInfo.setStatus(6);
            storeOrderInfo.setRefundStatus(0);
            storeOrderInfo.setIsDel(0);
//            storeOrderInfo.setPayPrice(convertDouble2BigDecimal(clearanceAmount.getNetPrice())
//                    .add(convertDouble2BigDecimal(clearanceAmount.getMerchantCustomsDuty()))
//                    .subtract(convertDouble2BigDecimal(clearanceAmount.getBeyondPromotion()))
//                    .subtract(convertDouble2BigDecimal(clearanceAmount.getMerchantPromotion())));
            // 单价+税费  * 数量
            storeOrderInfo.setPayPrice(convertDouble2BigDecimal((clearanceAmount.getNetPrice()+clearanceAmount.getMerchantCustomsDuty())*basicInfo.getQuantity()));

            // 优惠
            if (null != merchantPromotion){
                storeOrderInfo.setDeductionPrice(convertDouble2BigDecimal(merchantPromotion.getValue()));
            }
            storeOrderInfo.setCreateTime(new Date());
//            storeOrderInfo.setExchangeRate(convertDouble2BigDecimal(basicInfo.getCustomsDutyRate()));
            // 税费
            if (null != clearanceAmount){
                storeOrderInfo.setTaxPrice(convertDouble2BigDecimal(clearanceAmount.getMerchantCustomsDuty()));
            }
            //todo
//            basicInfo.setMerchantSkuId("CT196151825361");
            if (null == storeProductAttrValue){
                log.error("查询商品信息异常:{}",basicInfo.getMerchantSkuId());
            }

            // local商品信息
            BeanUtils.copyProperties(storeProduct,storeOrderInfo);
            storeOrderInfo.setProductId(storeProduct.getId());
            storeOrderInfo.setKeyword(storeProduct.getKeyword());
            storeOrderInfo.setStoreName(storeProduct.getStoreName());
            storeOrderInfo.setCateId(storeProduct.getCateId());
            storeOrderInfo.setVipReducePrice(storeProduct.getVipPrice());
            storeOrderInfo.setNum(basicInfo.getQuantity());
            storeOrderInfo.setIsWzbsc(false);
            storeOrderInfo.setId(null);

            // 供应商ID
            storeOrderInfo.setSuppliersId(storeProduct.getSuppliersId());

            // 商品购物车信息
            StoreCartResponse storeCartResponse = new StoreCartResponse();
            storeCartResponse.setProductAttrUnique(storeProductAttrValue.getSourceSkuId());
            storeCartResponse.setType("product");
            storeCartResponse.setProductId(storeProductAttrValue.getProductId());
            storeCartResponse.setCartNum(basicInfo.getQuantity());
            storeCartResponse.setIsNew(true);
            StoreProductCartProductInfoResponse storeProductCartProductInfoResponse = new StoreProductCartProductInfoResponse();
            BeanUtils.copyProperties(storeProduct,storeProductCartProductInfoResponse);
            storeProductCartProductInfoResponse.setAttrInfo(storeProductAttrValue);
            storeProductCartProductInfoResponse.setImage(storeProductAttrValue.getImage());
            storeCartResponse.setProductInfo(storeProductCartProductInfoResponse);

            storeOrderInfo.setInfo(JSON.toJSONString(storeCartResponse));

            storeOrderInfo.setCreateTime(new Date());
            // 扩展字段
            storeOrderInfo.addFeature("merchantProductId",basicInfo.getMerchantProductId());
            storeOrderInfo.addFeature("productId",basicInfo.getProductId());
            storeOrderInfo.addFeature("merchantSkuId",basicInfo.getMerchantSkuId());
            storeOrderInfo.addFeature("skuId",basicInfo.getSkuId());
            storeOrderInfo.addFeature("merId",String.valueOf(queryStoreOrder.getMerId()));
            index++;
            storeOrderInfos.add(storeOrderInfo);

        }


        return storeOrderInfos;
    }

    private StoreProductAttrValue getProductAttrValueInfo(BieYangGoodsBasicInfoDto basicInfo) {
        String merchantSkuId = basicInfo.getMerchantSkuId();
        String platProductId = basicInfo.getProductId();
        if (StringUtils.isBlank(merchantSkuId)){
            return null;
        }
        StoreProductAttrValue storeProductAttrValue = null;
        if (merchantSkuId.startsWith("SUYUN") && merchantSkuId.split("SUYUN").length > 1){
            storeProductAttrValue = storeProductAttrValueService.getById(merchantSkuId.split("SUYUN")[1]);
        }else {
            storeProductAttrValue = storeProductAttrValueService.getOne(Wrappers.<StoreProductAttrValue>lambdaQuery().eq(StoreProductAttrValue::getSelfSourceSkuId, merchantSkuId));
        }
        if (Objects.isNull(storeProductAttrValue)){
            DingTalkMsgUtil.sendMsg(DingMsgEnum.PLAT,"别样订单匹配商品sku失败，开始使用规格匹配");
            // todo 目前固定lavitahk_切分
            String[] split = platProductId.split("lavitahk_");
            if (split.length>1){
                String barCode = split[1];
                String reslut = get(platUrl + "/inventory/api/v1/products/"+platProductId, "");
                if (StringUtils.isBlank(reslut)){
                    return null;
                }
                ApiProduct apiProduct = JSON.parseObject(reslut, ApiProduct.class);
                if (null == apiProduct || CollectionUtils.isEmpty(apiProduct.getSkus())){
                    return null;
                }
                String property = "";
                for (Sku skus : apiProduct.getSkus()) {
                    if (Objects.equals(skus.getId(),basicInfo.getSkuId())){
                        List<SaleAttribute> saleAttributes = skus.getSaleAttributes();
                        if (CollectionUtils.isEmpty(saleAttributes)){
                            break;
                        }
                        Map<String, String> attributeMap = saleAttributes.stream().collect(Collectors.toMap(SaleAttribute::getKey, SaleAttribute::getName));
                        property = attributeMap.get("SIZE");
                        if (StringUtils.isBlank(property)){
                            property = attributeMap.get("COLOR");
                        }
                        break;
                    }
                }
                if (StringUtils.isBlank(property)){
                    return null;
                }
                List<StoreProductAttrValue> attrValues = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery().eq(StoreProductAttrValue::getBarCode, barCode));
                for (StoreProductAttrValue attrValue : attrValues) {
                    if (attrValue.getSuk().contains(property)){
                        return attrValue;
                    }
                }
            }
        }
        return storeProductAttrValue;
    }


    private StoreOrder assembledStoreOrder(BieYangDataDto bieYangDataDto) {

        // 商品
        List<BieYangDataDto.SkuInfo> skus = bieYangDataDto.getSkus();
        // 清关信息
        BieYangOrderClearanceInfoDto clearanceInfo = bieYangDataDto.getClearanceInfo();
        // 发件人信息
        BieYangAddressDto shippingAddress = bieYangDataDto.getShippingAddress();
        // 订单信息
        BieYangInfoSummaryDto infoSummary = bieYangDataDto.getInfoSummary();
        StoreOrder storeOrder = new StoreOrder();
        storeOrder.setOutOrderId(infoSummary.getOrderId());
        storeOrder.setOrderId(getOrderId(infoSummary.getOrderId()));
        // 拆单数据
        if (null != infoSummary.getSplit() && infoSummary.getSplit()){
            storeOrder.addFeature(ByCommonConstant.IS_SPLIT,ByCommonConstant.IS_Y);
            storeOrder.addFeature(ByCommonConstant.MAIN_ORDER_ID,infoSummary.getMainOrderId());
        }

        storeOrder.setUid(6371);
        storeOrder.setRealName(shippingAddress.getLastName()+shippingAddress.getFirstName());
        storeOrder.setUserPhone(shippingAddress.getPhone());
        storeOrder.setAreaType(1);
        storeOrder.setUserAddress(StringUtils.defaultString(shippingAddress.getAddress1(),shippingAddress.getAddress2()));
        storeOrder.setFreightPrice(convertDouble2BigDecimal(infoSummary.getTotalShippingFee()));
        storeOrder.setTotalNum(skus.size());
//        storeOrder.setTotalPrice(convertDouble2BigDecimal(infoSummary.getTotalItemPrice()));
        storeOrder.setTotalPrice(convertDouble2BigDecimal(clearanceInfo.getTotalActualPay()));
        storeOrder.setTotalPostage(convertDouble2BigDecimal(infoSummary.getTotalShippingFee()));
        storeOrder.setPayPrice(convertDouble2BigDecimal(clearanceInfo.getTotalActualPay()));
        storeOrder.setPayPostage(convertDouble2BigDecimal(infoSummary.getTotalShippingFee()));
        storeOrder.setDeductionPrice(BigDecimal.ZERO);
        storeOrder.setCouponId(0);
        storeOrder.setCouponPrice(convertDouble2BigDecimal(infoSummary.getPromotionAmount()));
        storeOrder.setPaid(true);
        storeOrder.setPayTime(DateUtil.longToDate(clearanceInfo.getPaymentTime()));
        storeOrder.setPayType(clearanceInfo.getPaymentMethod());
        storeOrder.setCreateTime(DateUtil.longToDate(clearanceInfo.getPaymentTime()));
        storeOrder.setCreateName("SYS");
        // 代发货
        storeOrder.setStatus(6);
        storeOrder.setRefundStatus(0);
        storeOrder.setRefundReasonWapImg("");


        storeOrder.setDeliveryName("");
        storeOrder.setIsDel(false);
        // todo 暂订
        storeOrder.setMerId(126);
        storeOrder.setShippingType(1);
        storeOrder.setPushStatus(0);

        storeOrder.setProvince(shippingAddress.getState());
        storeOrder.setCity(shippingAddress.getCity());
        storeOrder.setDistrict(shippingAddress.getDistrict());
        storeOrder.setDetail(shippingAddress.getAddress1());
        storeOrder.setIdCard(clearanceInfo.getIdentityNumber());
        storeOrder.setSource(9);
        // 支付单号
        storeOrder.setPayNo(clearanceInfo.getPaymentOrderId());
        storeOrder.setUnique(UUID.randomUUID().toString());
        storeOrder.setPayName(clearanceInfo.getLastName()+clearanceInfo.getFirstName());

        storeOrder.setRemark("BIE_YANG");
        return storeOrder;
    }

    private String getOrderId(String orderId) {
        return "BY"+orderId.replace("-","");
    }

    public BigDecimal convertDouble2BigDecimal(Double value){
        return null == value?BigDecimal.ZERO:BigDecimal.valueOf(value).setScale(2, RoundingMode.HALF_UP);

    }

    private void validateOrderExist(List<BieYangDataDto> bieYangDataDtos) {
        List<String> orderIds = bieYangDataDtos.stream().filter(item -> null != item.getInfoSummary() && StringUtils.isNotBlank(item.getInfoSummary().getOrderId()))
                .map(k -> k.getInfoSummary().getOrderId()).collect(Collectors.toList());
        List<StoreOrder> storeOrderList = storeOrderService.list(Wrappers.<StoreOrder>lambdaQuery().in(StoreOrder::getOutOrderId, orderIds));
        if (CollectionUtils.isEmpty(storeOrderList)){
            return;
        }
        Map<String, StoreOrder> map = storeOrderList.stream().collect(Collectors.toMap(StoreOrder::getOutOrderId, v -> v));
        bieYangDataDtos.removeIf(bieYangDataDto -> null == bieYangDataDto.getInfoSummary() || StringUtils.isBlank(bieYangDataDto.getInfoSummary().getOrderId()) || map.containsKey(bieYangDataDto.getInfoSummary().getOrderId()));
    }

    public static String get(String url, String params) {
        MultiValueMap<String,String> header = new LinkedMultiValueMap<>();
        header.put("Authorization",Collections.singletonList(platKey));
        return request(url, params, header, HttpMethod.GET, MediaType.APPLICATION_JSON);
    }
    public static String get(String url, String params, MultiValueMap<String, String> headers) {
        return request(url, params, headers, HttpMethod.GET, MediaType.APPLICATION_JSON);
    }

    public static String post(String url, String params) {
        MultiValueMap<String,String> header = new LinkedMultiValueMap<>();
        header.put("Authorization",Collections.singletonList(platKey));
        return request(url, params, header, HttpMethod.POST, MediaType.APPLICATION_JSON);
    }
    public static String post(String url, String params, MultiValueMap<String, String> headers) {
        return request(url, params, headers, HttpMethod.POST, MediaType.APPLICATION_JSON);
    }

    /**
     * http请求
     *
     * @param url
     * @param params    请求参数
     * @param headers   请求头
     * @param method    请求方式
     * @param mediaType 参数类型
     * @return
     */
    public static String request(String url, Object params, MultiValueMap<String, String> headers, HttpMethod method, MediaType mediaType) {
        if (url == null || url.trim().isEmpty()) {
            return null;
        }
        RestTemplate client = new RestTemplate();
        // header
        HttpHeaders httpHeaders = new HttpHeaders();
        if (headers != null) {
            httpHeaders.addAll(headers);
        }
        // 提交方式：表单、json
        httpHeaders.setContentType(mediaType);
        HttpEntity<Object> httpEntity = new HttpEntity(params, httpHeaders);
        ResponseEntity<String> response = client.exchange(url, method, httpEntity, String.class);
        return response.getBody();
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
//        fetch();
//        try {
//            FileInputStream fis = new FileInputStream(new File("D:\\bieyang\\品牌new.xlsx")); //替换为你的Excel文件路径
//
//            //创建一个工作簿
//            Workbook workbook = new XSSFWorkbook(fis);
//            //获取第一个工作表
//            Sheet sheet = workbook.getSheetAt(0);
//
//            int index = 0;
//            for (Row cells : sheet) {
//                index++;
//                if (index == 1){
//                    continue;
//                }
//                if (null==cells.getCell(0)){
//                    continue;
//                }
//
//                Integer id = (int) cells.getCell(0).getNumericCellValue();
//                String categoryId = "";
//                if (cells.getCell(16)!=null){
//                    categoryId = String.valueOf(cells.getCell(16).toString());
//                }
//                String enName = "";
//                if (null != cells.getCell(17)){
//                    enName = String.valueOf(cells.getCell(17).toString());
//                }
//                String zhName = "";
//                if (null != cells.getCell(18)){
//                    zhName = String.valueOf(cells.getCell(18).toString());
//                }
//                if (StringUtils.isBlank(categoryId)){
//                    continue;
//                }
//
//                System.out.println(id+"--"+categoryId+"--"+enName+"--"+zhName);
//
////                CategoryMatch categoryMatch = categoryMatchService.getById(id);
////                if (null == categoryMatch){
////                    continue;
////                }
////                categoryMatch.setByCategoryId(categoryId);
////                categoryMatch.addFeature("byCategoryEnName",enName);
////                categoryMatch.addFeature("byCategoryZhName",zhName);
////                System.out.println(categoryMatchService.updateById(categoryMatch));
//
//                StoreBrand storeBrand = storeBrandService.getById(id);
//                if (null == storeBrand){
//                    continue;
//                }
//                storeBrand.addFeature("byBrandEnName",enName);
//                storeBrand.addFeature("byBrandZhName",zhName);
//                storeBrand.setByBrandId(categoryId);
//                boolean b = storeBrandService.updateById(storeBrand);
//                System.out.println(b);
//                System.out.println(index);
//
//            }
//
//            workbook.close();
//            fis.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }

    public static void main(String[] args) {
//        try {
//            FileInputStream fis = new FileInputStream(new File("D:\\WorkSpace\\suyun\\back\\crmeb-server-new\\src\\main\\java\\com\\zbkj\\crmeb\\task\\bieyang\\速云品牌列表(1).xlsx")); //替换为你的Excel文件路径
//
//            //创建一个工作簿
//            Workbook workbook = new XSSFWorkbook(fis);
//            //获取第一个工作表
//            Sheet sheet = workbook.getSheetAt(0);
//
//            int index = 0;
//            for (Row cells : sheet) {
//                index++;
//                if (index == 1){
//                    continue;
//                }
//                Integer id = (int) cells.getCell(0).getNumericCellValue();
//                String categoryId = "";
//                if (cells.getCell(16)!=null){
//                    categoryId = String.valueOf(cells.getCell(16).toString());
//                }
//                String enName = "";
//                if (null != cells.getCell(17)){
//                    enName = String.valueOf(cells.getCell(17).toString());
//                }
//                String zhName = "";
//                if (null != cells.getCell(18)){
//                    zhName = String.valueOf(cells.getCell(18).toString());
//                }
//                if (StringUtils.isBlank(categoryId)){
//                    continue;
//                }
//
//                System.out.println(id+"--"+categoryId+"--"+enName+"--"+zhName);
//
//            }
//
//            workbook.close();
//            fis.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }
}
